//
//  HMOauthViewController.swift
//  sinaweibo
//
//  Created by WGP on 16/4/9.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

import SVProgressHUD

class HMOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURLRequest(URL: getOauthURL())
        webView.loadRequest(url)
        
//        家在的时候显示正在加载的窗口
        SVProgressHUD.showWithStatus("正在拼命加载中...")
        SVProgressHUD.setDefaultMaskType(.Gradient)
       
        setupBarItem()
        
//        HMPrint(NSHomeDirectory());
//        HMPrint(NSBundle.mainBundle().bundlePath);
    }

    private func setupBarItem()
    {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: Selector("didFill"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: Selector("didCancel"))
    }
    
//    MARK: - 监听方法
    @objc private func didFill()
    {
//        使用webView执行js代码
        let js = "document.getElementById('userId').value = '18225529869';document.getElementById('passwd').value = 'abc18225529869'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    @objc private func didCancel()
    {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
//    MARK: - 返回请求授权URL的私有方法
    private func getOauthURL()-> NSURL
    {
        let urlStr = OauthUrl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
//        HMPrint(urlStr)
        return NSURL(string: urlStr)!
    }
    
    
//    MARK: - 懒加载webView
    private lazy var webView:UIWebView = UIWebView()
}


//MARK: - 拓展
extension HMOauthViewController: UIWebViewDelegate
{
//    webView是否应该开始加载URL请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlStr = request.URL?.absoluteString


//        登录成功后,在授权界面点击取消,"https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps"
//  点击授权后的重定向url "https://m.baidu.com/?code=4ea24038690d5b9d1e5496c5c6a26f31&from=844b&vit=fps"
        
//        判断是否是授权回调url
       let isOauthURL = urlStr!.hasPrefix(redirect_uri)
        
        if(isOauthURL)
        {
            
//            判断点击的是同意授权还是取消
            let query = request.URL?.query
            HMPrint(query)
            
            let codeString = "code="
            if query!.hasPrefix(codeString)
            {
//                截取字符串
                let code = (query! as NSString).substringFromIndex(codeString.characters.count)
                HMPrint("\(code)")
                
//               获取access_token,当使用post获取AccessToken成功后,下次输入密码后就不会再弹出授权按钮,会直接去获取AccessToken,如果想看到授权按钮就去取消授权
                
/*
        Optional({
        "access_token" = "2.00oqxoiD2thVQCfd35048f1c4BC1oB";
        "expires_in" = 157679999;
        "remind_in" = 157679999;
        uid = 3410703750;
        })
*/
                
              HMUserAccountViewModel.sharedInstance.loadAccessToken(code, loadAccessTokenCallBack: { (error) -> () in
                if error != nil
                {
                    HMPrint("加载acessToken出错了:\(error)")
                    
                    SVProgressHUD.showErrorWithStatus("网络不给力!")
                    
//                    延时关闭
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        
                        self.didCancel()
                        
                    })
                    return

                }
                
                HMPrint("加载AccessToken成功")
                
                //                关闭授权界面
                self.didCancel()
                //                跳转到欢饮界面
                
                
                let welcomeVC = HMWelcomeViewController()
                
                getApplicationDelegate.switchViewController(welcomeVC)
                
              })
                

                
            }else
            {
//               点击取消按钮 关闭控制器
                didCancel()
            }
            
            return false
            
        }else
        {
            return true
        }
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        if error?.code == 102
        {
//           点击取消
            return
        }
        
//       没网速的时候
        SVProgressHUD.showErrorWithStatus("网络不给力...")
        SVProgressHUD.setDefaultMaskType(.Gradient)
        dismissViewControllerAnimated(true, completion: nil)
    }
}











